<template>
  <div class="Generated">
    <div class="title">教学设计方案</div>
    <a-form-model layout="inline" :model="form" ref="ruleForm" style="height: 98%; overflow-y: scroll;">
      <a-spin size="large" :spinning="G_loading">
        <div class="messages" ref="chatContainer" >
          <div v-for="(data, i) in formList" :key="i" class="box_shadow">
            <!-- <div class="subTitle" v-if="data.titleStr">
              <div>
                <a-button size="small" type="danger">
                  <a-icon type="right" />
                </a-button>
                <span>{{ data.titleStr }}</span>
              </div>
            </div> -->
            <!-- <div class="tips" v-if="data.tips">{{ data.tips }}</div> -->

            <a-descriptions v-if="data.type == 1" :column="1" bordered>
              <a-descriptions-item v-for="(item, key) in data.detailsList" :key="key" :label="item.name" >
                <a-form-model-item v-show="item.edit" style="width: 100%; height: 100%" :prop="item.key"
                  :rules="{ required: true, message: ' ', trigger: 'blur' }">
                  <a-textarea v-model="form[item.key]" :rows="15" :id='`textarea_${key}`'>
                  </a-textarea>
                </a-form-model-item>

                <!-- <div v-show="!item.edit" v-html="form[item.key]" style="white-space: pre-wrap;"></div> -->
                <vue-markdown 
                  v-show="!item.edit"
                  :source="form[item.key]" :breaks="true" :typographer="true" :linkify="true" :highlight="false"
                ></vue-markdown>

                <div>
                  <i class="icon_edit" v-if="!item.edit" @click="editText(item, key)"></i>
                  <i class="icon_submit" v-if="item.edit" @click="(e) => {editSubmit(e, item)}"></i>
                  <i class="icon_close" v-if="item.edit" @click="item.edit = false; $forceUpdate()"></i>
                </div>
              </a-descriptions-item>
            </a-descriptions>

            <!-- <a-table v-if="data.type == 3" :columns="data.columns" :data-source="data.dataList">
            </a-table> -->

            <!-- 教学设计资料 -->
            <a-list v-if="data.type == 2" item-layout="vertical" size="large" :data-source="data.detailsList">
              <a-list-item slot="renderItem" key="item.url" slot-scope="item">
                <!-- <img slot="extra" width="135" height="75" alt="logo"
                  src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png" /> -->
                <a-list-item-meta>
                  <div slot="description" :href="item.url">
                    <div class="description_item">资料名: {{ item.title }}</div>
                    <div class="description_item">资料来源: {{ item.engine }}</div>
                    <div class="description_item">
                      链接: <a  @click="openLink(item)">点击访问</a>
                    </div>
                    <div class="description_item">
                      资料简介: {{ item.summary }}
                    </div>
                  </div>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
            
            <div v-if="data.describeHtml" v-html="data.describeHtml" style="white-space: pre-wrap;"></div>
          </div>
        </div>
      </a-spin>
      <div class="btn_area">
        <a-form-model-item>
          <!-- <a-button type="danger" @click="editSubmit"> 保存 </a-button> -->
          <a-button type="danger" @click="downloadClass" v-if="sessionId"> 下载课件 </a-button>
        </a-form-model-item>
      </div>
    </a-form-model>
  </div>
</template>

<script>
const columns = [
  {
    title: "时间分配",
    dataIndex: "name",
    key: "name",
    ellipsis: true,
    align: "center",
  },
  {
    title: "教学环节",
    dataIndex: "name1",
    key: "name1",
    ellipsis: true,
    align: "center",
  },
  {
    title: "教师活动",
    dataIndex: "name2",
    key: "name2",
    ellipsis: true,
    align: "center",
  },
  {
    title: "学生行为",
    dataIndex: "name3",
    key: "name3",
    ellipsis: true,
    align: "center",
  },
];

import VueMarkdown from 'vue-markdown';
import download from 'downloadjs';
export default {
  name: "Generated",
  props: {},

  components: {
    VueMarkdown
  },

  data() {
    return {
      formList: [
        {
          detailsList: [
            // {
            //   name: "教学内容",
            //   key: "jxnr",
            //   jxnr: ``,
            //   loading: false,
            //   edit: false,
            // },
            // {
            //   name: "学情分析",
            //   key: "xqfx",
            //   xqfx: ``,
            //   loading: false,
            //   edit: false,
            // },
            // {
            //   name: "教学目标",
            //   key: "jxmb",
            //   jxmb: ``,
            //   loading: false,
            //   edit: false,
            // },
            // {
            //   name: "教学评价",
            //   key: "jxpj",
            //   jxpj: ``,
            //   loading: false,
            //   edit: false,
            // },
          ],
          titleStr: "",
          type: 1,
        },
        {
          detailsList: [
            // {
            //   name: "《狼牙山五壮士》教学设计(1)",
            //   url: "www.baidu.com",
            //   describe: "分析和解择了关于《狼牙山五壮士》核心主题及教学重难点",
            //   img: "",
            // },
            // {
            //   name: "《狼牙山五壮士》教学设计(1)",
            //   url: "www.baidu.com",
            //   describe: "分析和解择了关于《狼牙山五壮士》核心主题及教学重难点",
            //   img: "",
            // },
            // {
            //   name: "《狼牙山五壮士》教学设计(1)",
            //   url: "www.baidu.com",
            //   describe: "分析和解择了关于《狼牙山五壮士》核心主题及教学重难点",
            //   img: "",
            // },
          ],
          tips: "以下是我为您我到的教学设计资料：",
          titleStr: "",
          type: 2,
        },
        // {
        //   dataList: [],
        //   columns: columns,
        //   type: 3,
        // },
        // {
        //   describeHtml: `<div>教学方宾在Xx教学环节需要使用xx教具。</div><div>教学方宾在Xx教学环节需要使用xx教具。
        // 本教学方宾使用的学习科学及游戏化学习理论是：</div>`,
        //   type: 4,
        // },
      ],
      form: {},
    };
  },
  mounted() {
    this.scrollToBottom();
    console.log(this.sessionId)
  },

  computed: {
    // contentList() {
    //   return this.$store.state.contentList
    // }
    jxnr() {
      return this.$store.state.jxnr
    },
    xqfx() {
      return this.$store.state.xqfx
    },
    jxmb() {
      return this.$store.state.jxmb
    },
    jxpj() {
      return this.$store.state.jxpj
    },
    jxgc() {
      return this.$store.state.jxgc
    },
    jcjj() {
      return this.$store.state.jcjj
    },
    jxsjzl() {
      return this.$store.state.jxsjzl
    },
    selectForm() {
      return this.$store.state.form
    },
    sessionId() {
      return this.$store.state.sessionId
    },
    G_loading() {
      return this.$store.state.G_loading
    },
  },

  watch: {
    formList: {
      handler(newVal) {
        let obj = {};
        newVal.forEach((item) => {
          // console.log(item, ":item");
          if (item.type == 1) {
            item.detailsList.forEach((j) => {
              obj[j.key] = j[j.key];
            });
          }
        });
        // console.log(obj, "obj");
        this.form = obj;
        this.$forceUpdate();
      },
      deep: true,
      immediate: true,
    },


    jxnr: {
      handler(n) {
        if (n) {
          // console.log(this.formList, "this.formList")
          this.formList[0].detailsList[0] = {
            name: "教学内容",
            key: "jxnr",
            jxnr: n,
            loading: false,
            edit: false,
          }
          this.form.jxnr = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    xqfx: {
      handler(n) {
        if (n) {
          this.formList[0].detailsList[1] = {
            name: "学情分析",
            key: "xqfx",
            xqfx: n,
            loading: false,
            edit: false,
          }
          this.form.xqfx = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    jxmb: {
      handler(n) {
        if (n) {
          this.formList[0].detailsList[2] = {
            name: "教学目标",
            key: "jxmb",
            jxmb: n,
            loading: false,
            edit: false,
          }
          this.form.jxmb = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    jxpj: {
      handler(n) {
        if (n) {
          this.formList[0].detailsList[3] = {
            name: "教学评价",
            key: "jxpj",
            jxpj: n,
            loading: false,
            edit: false,
          }
          this.form.jxpj = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    jxgc: {
      handler(n) { 
        if (n) {
          this.formList[0].detailsList[4] = {
            name: "教学过程",
            key: "jxgc",
            jxgc: n,
            loading: false,
            edit: false,
          }
          this.form.jxgc = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    jcjj: {
      handler(n) {
        if (n) {
          this.formList[0].detailsList[5] = {
            name: "教参教具",
            key: "jcjj",
            jcjj: n,
            loading: false,
            edit: false,
          }
          this.form.jcjj = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    jxsjzl: {
      handler(n) {
        console.log(n)
        if (n) {
          this.$set(this.formList[1], 'detailsList', n)
          // this.form.jcjj = n;
          this.$forceUpdate();
        }
      },
      deep: true,
      immediate: true,
    },
    selectForm: {
      handler(n) {
        if (n) {
          this.$set(this.formList[0], 'titleStr', `${n.userName || ''} ${this.$dayjs().format('YYYY-MM-DD')}`)
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {

    editText(item, index) {
      item.edit = true;
      let textarea = document.getElementById(`textarea_${index}`)
      // console.log(textarea);
      setTimeout(() => {
        textarea.focus();
      })
      this.$forceUpdate()
    },
    openLink(item) {
      window.open(item.url);
    },
    scrollToBottom() {
      const container = this.$refs.chatContainer;
      container.scrollTop = container.scrollHeight;
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    putData(type, content, jtem) {
      this.$axios.put(`/api/v1/chains/chat`, {
        "session_id": this.sessionId,
        "step": type,
        "content": content
      })
        .then(res => {
          if (res.status == 200) {
            let data = res.data.content;
            console.log(data, "???")
            jtem.edit = false;
            this.$store.commit(`set${type}`, data);

            this.$nextTick(() => {
              if (!this.jxnr) {
                return false
              } else if (!this.xqfx) {
                return false
              } else if (!this.jxmb) {
                this.$emit("changeInitpush", "您已修改确认教学内容分析和学情分析,下面我可以开始帮您撰写学习目标了吗?")
              } else if (!this.jxpj) {
                this.$emit("changeInitpush", "您已修改确认教学目标,下面我可以开始帮您撰写教学评价了吗?")
              } else if (!this.jxgc) {
                this.$emit("changeInitpush", "您已修改确认教学评价,下面我可以开始帮您撰写教学过程了吗?")
              } else if (!this.jcjj) {
                this.$emit("changeInitpush", "您已修改确认教学过程,下面我可以开始帮您撰写教参教具了吗?")
              }else {
                this.$emit("changeInitpush", "对了，我还能为您搜集一些关于这部分教学设计的参考资料和教学参考视频，您想要看看吗？")

                console.log('================教学设计资料=====================')
                // this.searchData();
              }
            })
          }
        }).catch(err => {
          this.$message.error(err);
        })
    },

    
    editSubmit(e) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.formList.forEach(item => {
            if (item.detailsList) {
              item.detailsList.forEach(jtem => {
                if (jtem.edit) {
                  jtem.edit = false;
                  this.$forceUpdate()
                  this.putData(jtem.key, this.form[jtem.key], jtem)
                }
              })
            }
          })


        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    searchData() {
      this.$store.commit(`setG_loading`, true);
      
      this.$axios.get(`/api/v1/chains/chat/search?session_id=${this.sessionId}`).then(res => {
        if (res.status == 200) {
          this.$store.commit(`setG_loading`, false);
          this.$set(this.formList[1], 'detailsList', res.data)
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    downloadClass() {
      this.$axios.get(`/api/v1/chains/chat/download/${this.sessionId}`,  {
        responseType: 'blob'
      }).then(res => {
        const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
        console.log(downloadUrl)

        let xhr = new XMLHttpRequest();
        xhr.open('GET', downloadUrl, true);
        xhr.responseType = 'blob';
        xhr.onload = function() {
          if (xhr.readyState === 4 && xhr.status === 200) {
            let reader = new FileReader();
            reader.onload = function() {
              let dataUrl = reader.result;
              let a = document.createElement('a');
              a.href = dataUrl;
              a.download = '我的课程.doc';
              document.body.appendChild(a);
              a.click();
            };
  
            reader.readAsDataURL(xhr.response);
          }
        };
  
        xhr.send();


        // this.$axios.get( `/api/v1/chains/chat/download/${this.sessionId}`, { responseType: 'blob' })
        // .then(response => {
        //   const blob = new Blob([response.data]);
        //   const url = URL.createObjectURL(blob);
        //   const link = document.createElement('a');
        //   link.href = url;
        //   link.download = 'aaaa.docx';
        //   link.click();
        // });

        return false;
        // let xhr = new XMLHttpRequest();
        // xhr.open('get', `/api/v1/chains/chat/download/${this.sessionId}`, true);
        // xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        // xhr.setRequestHeader('Authorization', localStorage.getItem('Authorization'));
        // xhr.responseType = "blob"; // 返回类型blob
        // xhr.send(); // 发送ajax请求
        // xhr.onreadystatechange = function () {
        //   if (xhr.readyState === XMLHttpRequest.DONE) {
        //     //创建blob对象
        //     const blob = new Blob([xhr.response], { type: 'application/mxword' });
        //     const fileName = '';
        //     //创建下载元素
        //     const downloadElement = document.createElement('a');
        //     // 创建下载的链接
        //     const href = window.URL.createObjectURL(blob);
        //     downloadElement.href = href;
        //     downloadElement.download = '我的课程aaa.doc'; // 下载后文件名
        //     document.body.appendChild(downloadElement);
        //     downloadElement.click(); // 点击下载
        //     document.body.removeChild(downloadElement); // 下载完成移除元素
        //     window.URL.revokeObjectURL(href); // 释放掉blob对象
        //   }
        // }

        return false;
      }).catch(err => {
        this.$message.error(err);
      })
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.Generated {
  .ant-list-vertical .ant-list-item-extra {
    margin-left: 20px;
  }

  .ant-list-item {
    background: #ffe9e9;
    padding: 10px;
    border: none;
    margin-bottom: 10px;
    border-radius: 8px;

    .ant-list-item-main {
      padding-top: 5px;
    }

    .ant-list-vertical .ant-list-item-meta {
      margin-bottom: 0;
    }
  }
}
</style>
<style scoped lang="less">

/deep/ .ant-spin-nested-loading > div > .ant-spin .ant-spin-dot {
  position: fixed!important;
  right: 22%!important;
  top: 52% !important;
  left: auto !important;
}

.Generated {
  height: 100%;
  position: relative;
  padding: 40px 10px !important;
  box-sizing: border-box;

  /deep/ .ant-descriptions-item-label {
    background: rgba(255, 38, 38, 0.1);
    color: rgba(10, 15, 44, 0.65);
    font-size: 15px;
  }

  /deep/ .ant-descriptions-row {
    margin-bottom: 10px;
  }
  /deep/ .ant-descriptions-bordered .ant-descriptions-item-label {
    width: 60px !important;
    text-align: center;
  }

  >.title {
    padding: 12px 10px;
    box-sizing: border-box;
  }

  .messages {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    overflow-y: scroll;

    ::-webkit-scrollbar {
      display: none;
    }

    scrollbar-width: none;
    -ms-overflow-style: none;
    scrollbar-width: none;

    padding: 10px;

    >div {
      padding: 10px 15px;
      margin-bottom: 10px;
      box-sizing: border-box;

      .subTitle {
        height: 36px;
        line-height: 36px;

        span {
          margin-left: 10px;
          padding: 4.5px 10px;
          box-sizing: border-box;
          border-radius: 36px;
          border: 1px solid #dfdfdf;
        }
      }

      .description_item {
        color: #000;
        font-size: 12px;
      }
    }
  }

  .title {
    height: 40px;
    width: 100%;
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
    color: rgba(154, 0, 0, 1);
    font-size: 16px;;
  }

  .btn_area {
    height: 50px;
    width: 100%;
    position: absolute;
    z-index: 10;
    left: 0;
    bottom: 0;
    text-align: right;
    background: #fff;

    button {
      margin-left: 10px;
    }
  }

  /deep/ .ant-descriptions-item-content {
    position: relative;
    padding: 20px 24px;
  }

  .icon_edit {
    display: inline-block;
    position: absolute;
    right: 10px;
    bottom: 5px;
    cursor: pointer;
    width: 16px;
    height: 16px;
    background: url('../assets/img/edit.png') 0 0 no-repeat;
    background-size: 100%;
  }
  .icon_submit {
    display: inline-block;
    position: absolute;
    right: 30px;
    bottom: 3px;
    cursor: pointer;
    width: 16px;
    height: 16px;
    background: url('../assets/img/gou.png') 0 0 no-repeat;
    background-size: 100%;
  }
  .icon_close {
    display: inline-block;
    position: absolute;
    right: 10px;
    bottom: 3px;
    cursor: pointer;
    width: 16px;
    height: 16px;
    background: url('../assets/img/cha.png') 0 0 no-repeat;
    background-size: 100%;
  }
}
</style>